<template>
    <div v-loading="loading" element-loading-text="加载中..." :id="`thumb_wrapper_${props._pairs_id}`" class="thumb-wrapper">
        <canvas :id="`thumb_canvas_${props._pairs_id}`"></canvas>
    </div>
</template>

<script setup>
import API from '@/js/api';
import { fabric } from 'fabric';
import { onMounted, onUnmounted, ref, watch, inject } from 'vue';
import { createLabel } from '@/js/models/LabelBase.js';

const name = 'LabelThumb';
let vueApp = inject('vueApp');
const props = defineProps(['_dataset_info', '_rindex', '_cindex', '_pairs_id', '_image_url', '_label_url', '_loading_status', '_loading_remote']);
const emit = defineEmits(['imageLoaded']);

// 对应的fabricjs对象和属性
let _canvas = null;
let _image = null;
let _label_result = null;

// 定义是否加载中
const loading = ref(false);

// 监听可视化状态的变化
watch(
    () => props._loading_status,
    (newValue, oldValue) => {
        // console.log(`[${props._rindex}, ${props._cindex}] loading status changed from [${oldValue}] to [${newValue}]`);
        if (props._loading_remote && newValue == true) {
            loadImage();
        }
    }
);

// 对象的绘制方法
async function getImageURL(image_url) {
    return API.api_url('LoadImage', { image_path: image_url });
}

function initCanvas() {
    // console.log(`the ImageRegion component is now mounted.`)
    let canvas_wrapper = document.getElementById(`thumb_wrapper_${props._pairs_id}`);
    let canvas_size = {
        width: canvas_wrapper.clientWidth,
        height: canvas_wrapper.clientHeight
    };
    _canvas = new fabric.Canvas(`thumb_canvas_${props._pairs_id}`, {
        backgroundColor: 'gray',
        width: canvas_size.width,
        height: canvas_size.height,
        fireRightClick: true,
        stopContextMenu: true
    });

    // console.log('props._loading_status = ', props._loading_status);
    if (props._loading_remote == false || props._loading_status == true) {
        loadImage();
    }
}

function clearCanvas() {
    _canvas && _canvas.clear();
    _image = null;
    return true;
}

async function loadImage() {
    // 清空canvas上的内容（背景颜色也被清空）
    clearCanvas();
    loading.value = true;

    // 动态获取到image的url
    let img_url = await getImageURL(props._image_url);
    if (!img_url) {
        return;
    }
    // console.log(`image_url = ${img_url}`);

    // 正式加载图片资源
    let canvas_wrapper = document.getElementById(`thumb_wrapper_${props._pairs_id}`);
    let canvas_size = {
        width: canvas_wrapper.clientWidth,
        height: canvas_wrapper.clientHeight
    };
    fabric.Image.fromURL(
        img_url,
        async (img) => {
            loading.value = false;
            _image = img;
            img.set({
                originX: 'center',
                originY: 'center',
                hoverCursor: 'pointer',
                left: canvas_size.width / 2,
                top: canvas_size.height / 2,
                hasControls: false,
                hasBorders: false,
                selectable: false
            });
            let img_size = {
                width: img.width,
                height: img.height我看昨天工单里面有那种左虚右实或者
            };
            _canvas.add(img);

            let center_point = {
                x: canvas_size.width / 2,
                y: canvas_size.height / 2
            };
            let zoom = canvas_size.width / img_size.width;
            _canvas.zoomToPoint(center_point, zoom);
            // console.log(`imageLoaded pairs_id = ${props._pairs_id}`);
            if (props._loading_remote) {
                emit('imageLoaded', {
                    rindex: props._rindex,
                    cindex: props._cindex,
                    pairs_id: props._pairs_id,
                    loaded: true
                });
            }

            // 绑定当前的canvas和image
            await loadLabel();
            _label_result && _label_result.bindCanvas(_canvas, _image, null);
            _label_result && _label_result.setEditableMode(false);
        },
        (error) => {
            console.error('Error loading image:', error);
            if (props._loading_remote) {
                emit('imageLoaded', {
                    rindex: props._rindex,
                    cindex: props._cindex,
                    pairs_id: props._pairs_id,
                    loaded: false
                });
            }
        },
        { crossOrigin: 'anonymous' }
    );
    return true;
}

async function loadLabel() {
    // 加载对应的标注结果
    if (!props._label_url) {
        return;
    }

    let algo_type = vueApp.getAlgoType();
    _label_result = await createLabel(algo_type, props._dataset_info.label_format);
    let result = await API.invoke('LoadLabel', {
        dataset_id: props._dataset_info.id,
        dataset_supertype: algo_type.supertype,
        dataset_type: props._dataset_info.dataset_type,
        label_format: props._dataset_info.label_format,
        image_path: props._image_url,
        label_path: props._label_url
    });
    if (result.code == 0) {
        _label_result.fromJson(result.msg);
    }
    // console.log('_label_result = ', _label_result);
}

function handleResize() {
    // console.log('## LabelThumb.vue handleResize');
    if (!_canvas || !_image) {
        return;
    }

    let canvas_wrapper = document.getElementById(`thumb_wrapper_${props._pairs_id}`);
    let canvas_size = {
        width: canvas_wrapper.clientWidth,
        height: canvas_wrapper.clientHeight
    };
    let center_point = {
        x: 0,
        y: 0
    };
    let img_size = {
        width: _image.width,
        height: _image.height
    };

    let zoom = canvas_size.width / img_size.width;
    // console.log(`thumb_wrapper_${props._pairs_id} canvas_size = `, canvas_size);
    // console.log(`thumb_wrapper_${props._pairs_id} img_size = `, img_size);
    // console.log(`thumb_wrapper_${props._pairs_id} zoom = `, zoom);
    _canvas.setDimensions(canvas_size);
    _canvas.zoomToPoint(center_point, zoom);
}

onMounted(() => {
    // console.log(`_image_url = ${props._image_url}, _label_url = ${props._label_url}`);
    initCanvas();
    window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
    clearCanvas();
    window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.thumb-wrapper {
    width: 100%;
    height: 100%;
}
</style>
